package com.wzs.controller;

import com.google.gson.Gson;
import com.wzs.dao.impl.UserDao;
import com.wzs.model.User;
import com.wzs.model.UserCondition;
import com.wzs.service.IUserService;
import com.wzs.service.impl.UserService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

/**
 * @author miaomiao
 * @version 1.0.0
 * @ClassName UserServlet.java
 * @Description TODO
 * @createTime 2021-06-19- 15:00:00
 */
public class UserServlet extends HttpServlet {

    private IUserService userService;

    public IUserService getUserService() {
        return userService;
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    public void init() throws ServletException {
        UserDao ud = new UserDao();
        UserService us = new UserService();
        us.setUserDao(ud);
        userService = us;
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String operation = request.getParameter("operation");

        if ("getUserList".equalsIgnoreCase(operation)) {
            getUserList(request, response);
        }


    }

    private void getUserList(HttpServletRequest request, HttpServletResponse response) throws IOException {

        System.out.println("进入到查询操作");

        String name = request.getParameter("name");
        UserCondition condition = new UserCondition();

        condition.setName(name);

        ArrayList<User> userList = userService.getUserListByCondition(condition);

        Gson g = new Gson();
        String uList = g.toJson(userList);

        //System.out.println(uList);

        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        out.println(uList);
        out.flush();
        out.close();

    }
}
